package com.weiyu.bultrasound.core.service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.weiyu.bultrasound.common.util.SnowFlake;
import com.weiyu.bultrasound.core.dao.ApplicationsMapper;
import com.weiyu.bultrasound.core.model.common.FilesCodeEnum;
import com.weiyu.bultrasound.core.model.entity.Applications;
import com.weiyu.bultrasound.core.model.entity.Files;
import com.weiyu.bultrasound.core.model.request.CommonRequest;
import com.weiyu.bultrasound.core.model.request.ApplyRequestBody;
import com.weiyu.bultrasound.core.model.request.FilesRequest;
import com.weiyu.bultrasound.core.model.request.UploadRequest;
import com.weiyu.bultrasound.core.model.response.CommonResponse;
import com.weiyu.bultrasound.core.model.response.ResponseHeader;
import com.weiyu.bultrasound.core.model.vo.ApplicationsVO;
import com.weiyu.bultrasound.core.service.ApplicationsService;
import com.weiyu.bultrasound.core.service.FilesService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 *@description 
 *@author abner chow
 *@date 2019-08-08 11:16
 */
@Service
public class ApplicationsServiceImpl implements ApplicationsService {

    private static final Logger logger = LoggerFactory.getLogger(ApplicationsServiceImpl.class);

    @Autowired
    ApplicationsMapper applicationsMapper;

    @Autowired
    FilesService filesService;

    @Override
    public Applications get(Long id) {
        return applicationsMapper.getById(id);
    }

    /**
     * @description 根据id获取申请单视图实体
     * @Param: [id]
     * @Return: com.weiyu.bultrasound.core.model.vo.ApplicationsVO
     * @Author: abner chow
     * @Date: 2019/8/14 17:35
     */
    @Override
    public ApplicationsVO getById(Long id) {
        ApplicationsVO applicationsVO = new ApplicationsVO();
        Applications applications = applicationsMapper.getById(id);
        if (null != applications) {
            BeanUtils.copyProperties(applications, applicationsVO);
            applicationsVO.setFilesList(filesService.getByApplicationsId(id));
        }
        return applicationsVO;
    }

    /**
     * @description 保存
     * @Param: [applications]
     * @Return: java.lang.Boolean
     * @Author: abner chow
     * @Date: 2019/8/14 17:34
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean save(Applications applications) {
        Boolean flag = Boolean.FALSE;
        int i = 0;
        if (null != applications) {
            Applications exist = applicationsMapper.getById(applications.getId());
            if (exist == null) {
                i = applicationsMapper.insert(applications);
                if (i > 0) {
                    flag = Boolean.TRUE;
                }
            } else {
                i = applicationsMapper.updateById(applications);
                if (i > 0) {
                    flag = Boolean.TRUE;
                }
            }
        }
        return flag;
    }

    /**
     * @description 获取申请单分页列表
     * @Param: [param]
     * @Return: com.github.pagehelper.PageInfo<com.weiyu.bultrasound.core.model.vo.ApplicationsVO>
     * @Author: abner chow
     * @Date: 2019/8/14 17:34
     */
    @Override
    public PageInfo<ApplicationsVO> getByPage(Map param) {
        PageInfo<ApplicationsVO> result = new PageInfo<ApplicationsVO>();
        PageHelper.startPage((Integer) param.get("pageNum"), (Integer) param.get("pageSize"));
        List<Applications> applicationsList = applicationsMapper.getList(param);
        PageInfo<Applications> pageInfo = new PageInfo<>(applicationsList);
        if (null != pageInfo) {
            List<Applications> list = pageInfo.getList();
            List<ApplicationsVO> voList = new ArrayList<>();
            BeanUtils.copyProperties(pageInfo, result);
            list.forEach((Applications applications) -> {
                ApplicationsVO applicationsVO = new ApplicationsVO();
                BeanUtils.copyProperties(applications, applicationsVO);
                voList.add(applicationsVO);
            });
            result.setList(voList);
        }
        return result;
    }

    /**
     * @description 5G移动申请单处理
     * @Param: [commonRequest]
     * @Return: com.weiyu.bultrasound.core.model.response.CommonResponse
     * @Author: abner chow
     * @Date: 2019/8/14 17:33
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResponse tMIMedCartApply(CommonRequest<ApplyRequestBody> commonRequest) {
        CommonResponse commonResponse = new CommonResponse();
        ResponseHeader header = new ResponseHeader();
        int i = 0;
        if (null != commonRequest) {
            ApplyRequestBody applyRequestBody = commonRequest.getBody();
            List<Applications> patients = applyRequestBody.getPatients();
            String busCode = applyRequestBody.getBusCode();
            if (!CollectionUtils.isEmpty(patients)) {
                //过滤未存在的数据
                List<Applications> exist = patients.stream().filter(e -> checkByApplyCode(e.getApplyCode())).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(exist)) {
                    exist.forEach((Applications applications) -> {
                        applicationsMapper.updateByApplyCode(applications);
                    });
                    i = exist.size();
                }
                //过滤未存在的数据
                List<Applications> notExist = patients.stream().filter(e -> !checkByApplyCode(e.getApplyCode())).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(notExist)) {
                    SnowFlake snowFlake = new SnowFlake(2, 3);
                    notExist.forEach((Applications applications) -> {
                        applications.setId(snowFlake.nextId());
                        applications.setApplyDate(new Date());
                        applications.setStatus(1);
                        applications.setBusCode(busCode);
                        applications.setModifyTime(new Date());
                    });
                    i = applicationsMapper.insertByBatch(notExist);
                }
            }
            if (i > 0) {
                header.setResultCode("0");
                header.setResultDesc("成功");
            } else {
                header.setResultCode("1001");
                header.setResultDesc("失败");
                header.setErrorInfo("申请请求响应失败");
            }
        } else {
            header.setResultCode("1");
            header.setResultDesc("失败");
            header.setErrorInfo("请求参数不完整");
        }
        commonResponse.setHeader(header);
        return commonResponse;
    }


    /**
     * @description 文件上传
     * @Param: [uploadRequest]
     * @Return: java.lang.Boolean
     * @Author: abner chow
     * @Date: 2019/8/12 15:03
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean uploadFile(UploadRequest uploadRequest) {
        Boolean flag = Boolean.FALSE;
        if (null != uploadRequest) {
            Long applicationsId = uploadRequest.getId();
            Applications applications = applicationsMapper.getById(applicationsId);
            if( null != applications ){
                List<FilesRequest> list = uploadRequest.getFileList();
                if (null != applicationsId && !CollectionUtils.isEmpty(list)) {
                    SnowFlake snowFlake = new SnowFlake(2, 3);
                    List<Files> filesList = new ArrayList<>();
                    list.forEach((FilesRequest filesRequest) -> {
                        Files files = new Files();
                        BeanUtils.copyProperties(filesRequest, files);
                        files.setId(snowFlake.nextId());
                        files.setApplicationsId(applicationsId);
                        files.setTypeCode(getTypeCodeByName(filesRequest.getName()));
                        filesList.add(files);
                    });
                    flag = filesService.insertByBatch(filesList);
                    //更新检测时间
                     int i = applicationsMapper.updateById(Applications.builder().id(applicationsId).status(3).beginTime(new Date(new Long(uploadRequest.getBeginTime()))).build());
                     if( flag && i > 0 ){
                         flag = Boolean.TRUE;
                     }
                }
            }
        }
        return flag;
    }


    /**
     * @description 根据申请代码检测是否已存在申请记录
     * @Param: [applyCode]
     * @Return: java.lang.Boolean
     * @Author: abner chow
     * @Date: 2019/8/22 15:06
     */
    @Override
    public Boolean checkByApplyCode(String applyCode) {
        int i = applicationsMapper.countByApplyCode(applyCode);
        if( i > 0){
            return Boolean.TRUE;
        }else {
            return Boolean.FALSE;
        }
    }


    /**
     * @description 根据文件名获取文件类型code
     * @Param: [name]
     * @Return: java.lang.String
     * @Author: abner chow
     * @Date: 2019/8/13 13:57
     */
    protected static String getTypeCodeByName(String name) {
        String typeCode = "";
        if (StringUtils.hasText(name)) {
            int i = name.indexOf(".");
            if (i >= 0) {
                String suffix = name.substring(i + 1);
                typeCode = FilesCodeEnum.getCodeByDesc(suffix);
            }
        } else {
            logger.error("文件名不能为空");
        }
        return typeCode;
    }


    /**
     * @description 获取已上传但未同步的申请列表
     * @Param: []
     * @Return: java.util.List<com.weiyu.bultrasound.core.model.entity.Applications>
     * @Author: abner chow
     * @Date: 2019/8/27 16:29
     */
    @Override
    public List<Applications> getUnsynList() {
        Map param = new HashMap();
        param.put("status" , 3);
        return applicationsMapper.getList(param);
    }
}
